package com.xsz.oa.controller.sys;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 登录
 * 
 * @author xsz
 * @date 2015.11.22
 */
@Controller
public class LoginController {

	/**
	 * 访问该路径默认被/authc过滤器拦截，进行登录验证，如果成功则跳转到successUrl，否则放行
	 * 也就是说只有在登录验证失败的时候才会调用此方法，且失败信息放到request中,属性名为shiroLoginFailure。
	 * 
	 * @param req
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest req, Model model) {

		String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
		String error = null;

		// 还有很多错误类型，比如用户被锁定等，这里只写了2个常用的用户名密码错误
		if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
			error = "用户名或密码错误";
		} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
			error = "用户名或密码错误";
		} else if (exceptionClassName != null) {
			error = "其他错误：" + exceptionClassName;
		}

		model.addAttribute("error", error);

		return "login";
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login",method=RequestMethod.GET)
	public String login() {
		
		Subject subject = SecurityUtils.getSubject();
		
		//如果已经认证过了，或者已经记住我了，就直接到首页
		if (subject.isAuthenticated() || subject.isRemembered()) {
			return "redirect:/";
		}
		
		return "login";
	}
	
}
